package com.xlz.service;

import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import com.xlz.domain.AppInstance;

/**
 * 应用实例信息CRUD工具类.
 * @author 张蕾蕾
 * @date 2018 03 24
 */
public class AppInstanceService extends BaseJdbcService<AppInstance>{

	public AppInstanceService(DataSource dataSource) {
		super(dataSource);
	}

	public void insertOrUpdate(String appNo,String instanceIp) throws SQLException{
		// 发送心跳
		String sql = "update app_instance set update_time=now() where app_no=%s and register_instance_id=%s";
		String args[] = new String[3];
		int count = 0;
		args[0] = "'" + appNo + "'";
		args[1] = "'" + instanceIp + "'";
		count = executeUpdate(String.format(sql, args));
		if (count == 0) {
			// 插入记录
			args[0] = "'" + appNo + "'";
			args[1] = "'" + instanceIp + "'";
			args[2] = "now()";
			sql = "insert into app_instance(app_no,register_instance_id,create_time,update_time) values(%s,%s,%s,now())";
			count = executeUpdate(String.format(sql, args));
		}
	}
	
	public List<AppInstance> getAllByAppNo(String appNo){
		String sql = "select id, app_no,register_instance_id,create_time,update_time from app_instance where app_no='"+appNo+"'";
		return findAll(sql, AppInstance.class);
	}
	
	public List<AppInstance> getDeadAllByAppNo(String appNo,long deadTime){
		String sql = "select id, app_no,register_instance_id,create_time,update_time from app_instance where app_no = '"+appNo+"' and update_time < date_add(now(), interval -"+deadTime+" second)";
		return findAll(sql, AppInstance.class);
	}

	public boolean deleteByAppId(Long id) throws SQLException {
		String sql = "delete from app_instance where id="+id;
		return  executeUpdate(sql) > 0;
	}
	
	@Override
	public String getNamespace() {
		return "com.xlz.pojo.AppInstance.";
	}

	
}
